import React,{useEffect,useState} from 'react'
import './less/mean.less'
import { Form, Input, Button, message,Upload} from 'antd';
import {getUserDataApi,changeUserApi} from '../request/api'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { connect } from 'react-redux';

// 将图片转化为base64
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

// 限制图片的大小 2M
function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024/ 1024/ 1024  < 200;
  if (!isLt2M) {
    message.error('请上传小于200kb的图!');
  }
  return isJpgOrPng && isLt2M;
}


 function Means(props) { 
  const [loading,setLoading] = useState(false)
  const [imageUrl,setImageUrl] = useState("")


  // 点击上传
 const handleChange = info => {
    if (info.file.status === 'uploading') {
      setLoading(false)
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, imageUrl =>{
        setLoading(false)
        setImageUrl(imageUrl)
        // 存储图片信息
        localStorage.setItem('avatar',info.file.response.data.filePath)
        // 触发Header组件更新
        // props.addkey()
        window.location.reload()
      }
      );
    }
  };


  useEffect(()=>{
    getUserDataApi().then(res=>{
      if(res.errCode===0){
        message.success(res.message)
        // 存储到sessionStorage
        sessionStorage.setItem('username',res.data.usrname)
      }
    })
  },[])

  // 表单提交事件c
  const onFinish = (values)=>{
    if(values.username && values.username !== sessionStorage.getItem('username') && values.password.trim() === "")
    {
      // 表单提交。。。。
      changeUserApi({
        username:values.username,
        Password:values.password
      }).then(res=>{
        console.log(res);
        // 当修改成功的时候，不要忘了重新登录
        if(res.errCode===0){
          message.success(res.message)
        }
      })
    }
  }

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );


  return (
    <div className='means'>
    <Form
      name="basic"
      style={{width:'400px'}}
      autoComplete="off"
      onFinish={onFinish}
    >
      <Form.Item
        label="修改用户名"
        name="username"
      >
        <Input placeholder='请输入新用户名' />
      </Form.Item>

      <Form.Item
        label="修改密码"
        name="password"
      >
        <Input.Password placeholder='请输入新密码' />
      </Form.Item>

      <Form.Item
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit" style={{float:'right'}}>提交</Button>
      </Form.Item>
    </Form>
    <p>点击下方修改头像</p>
    <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action="/api/upload"
        beforeUpload={beforeUpload}
        onChange={handleChange}
        headers={{"cms-token":localStorage.getItem('cms-token')}}
      >
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
    </div>
  )
}
const mapDispatchToProps = (dispatch) => {
  return {
    addKey(){
      dispatch({type: "addKeyFn"})
    }
  }
}

export default connect(null,mapDispatchToProps)(Means)